<?php

namespace app\agentapi\controller\company;

use app\agentapi\controller\Controller;
use think\Cache;
use app\agent\model\wxapp\Wxapp as WxappModel;
use app\agent\model\store\Shop as StoreShopModel;
use think\Db;
use utils\Random;
use think\Config;
/**
 * 商户操作类
 * Class Category
 * @package app\store\controller\goods
 */
class Company extends Controller{
    /*
     * 商户列表
     */
    public function manageList(){
        //获取当前登录代理包含自己在内的所有下级agent_id
        $agent_wxapp_id=input('post.agent_wxapp_id');//小程序id
        $agent_user_id=input('post.agent_user_id');
        $loginInfo=Cache::get($agent_wxapp_id.$agent_user_id);
        $active=input('post.active');
        $shopName=input('post.agentName');

        $arr1='w.active';
        if($active==0){
            //待审核
            $arr2='=';
            $arr3='0';
        }elseif ($active==1){
            //已审核
            $arr2='=';
            $arr3='1';
        }else{
            //全部
            $arr2='in';
            $arr3=[0,1];
        }
        if(empty($agent_wxapp_id)){
            return json(['msg'=>'未获取到小程序id','code'=>'error','data'=>[]]);
        }
        if(empty($loginInfo)){
            return json(['msg'=>'登录信息不存在','code'=>'error','data'=>[]]);
        }
        //获取当前品牌的所有代理商id信息
        $return=Db::name('agent_user')->where(['pinpai_id'=>$loginInfo['loginUser']['pinpai_id']])->select();
        $agentIdarray=$this->get_all_child($return->toArray(),$loginInfo['loginUser']['agent_user_id']);
        $agentIdarray[]=(int)$loginInfo['loginUser']['agent_user_id'];
        //获取商户信息
        $pagenum=input('post.page_num');
        $page=isset($pagenum)&&is_numeric(input('post.page_num'))?intval($pagenum):1;
        $limit = 15;
        $offset=($page-1) * $limit;
        if($shopName){
            $shopInfo=Db::table('yoshop_wxapp')
                ->alias('w')
                ->join('yoshop_agent_user a','w.agent_id = a.agent_user_id')
                ->join('yoshop_store_shop s','w.wxapp_id = s.wxapp_id')
                ->where('w.agent_id','in' ,$agentIdarray)
                ->where(['a.real_name'=>['like','%'.$shopName.'%']])
                ->where($arr1,$arr2,$arr3)
                ->where('w.is_delete',0)
                ->field('w.*,a.type,s.shop_name,a.real_name')
                ->limit($offset,$page)
                ->paginate(15,false, [
                    'page'  =>$page
                ]);
        }else{
            $shopInfo=Db::table('yoshop_wxapp')
                ->alias('w')
                ->join('yoshop_agent_user a','w.agent_id = a.agent_user_id')
                ->join('yoshop_store_shop s','w.wxapp_id = s.wxapp_id')
                ->where('w.agent_id','in' ,$agentIdarray)
                ->where($arr1,$arr2,$arr3)
                ->where('w.is_delete',0)
                ->field('w.*,a.type,s.shop_name,a.real_name')
                ->limit($offset,$page)
                ->paginate(15,false, [
                    'page'  =>$page
                ]);
        }
        $shopInfo=$shopInfo->toArray();
        if(!empty($shopInfo['data'])){
            foreach ($shopInfo['data'] as $k=>$v){
                if($v['type']==0){
                    $shopInfo['data'][$k]['type_name']='品牌商';
                }elseif ($v['type']==1){
                    $shopInfo['data'][$k]['type_name']='城市运营商';
                }elseif ($v['type']==2){
                    $shopInfo['data'][$k]['type_name']='城市合伙人';
                }else{
                    $shopInfo['data'][$k]['type_name']='代言人';
                }
                if($v['active']==0){
                    $shopInfo['data'][$k]['status_name']='审核中';
                }else{
                    $shopInfo['data'][$k]['status_name']='已通过';
                }
            }
            return json(['msg'=>'获取成功','code'=>'success','data'=>$shopInfo]);
        }
        return json(['msg'=>'未查询到信息','code'=>'success','data'=>[]]);
    }
    /*
     * 获取代理子级
     */
    private function get_all_child($array,$id){
        $arr = array();
        foreach($array as $v){
            if($v['recommend_id']==$id){
                $arr[] = $v['agent_user_id'];
                $arr = array_merge($arr,$this->get_all_child($array,$v['agent_user_id']));
            };
        };
        return $arr;
    }
    /*
     * 判断商家进件是否需要选择商家类型
     */
    public function isSelect(){
        return json(['msg'=>'需要','code'=>'success','data'=>true]);
    }
    /*
     * 商户进件（门店信息）
     */
    public function manageInfoAdd(){
        //更新账户信息
        $agent_wxapp_id=input('post.agent_wxapp_id');//小程序id
        $agent_user_id=input('post.agent_user_id');
        $loginInfo=Cache::get($agent_wxapp_id.$agent_user_id);
        if(empty($agent_wxapp_id)){
            return json(['msg'=>'未获取到小程序id','code'=>'error','data'=>[]]);
        }
        if(empty($loginInfo)){
            return json(['msg'=>'登录信息不存在','code'=>'-10','data'=>[]]);
        }
        Db::startTrans();
        try{
            //添加 wxapp Setting StoreUser WxappHelp WxappPage WxappCategory表数据
            $wxappData['app_id']=0;//小程序AppID
            $wxappData['app_secret']=0;//小程序AppSecret
            $wxappData['mchid']=0;//微信商户号id
            $wxappData['apikey']=0;//微信支付密钥
            $wxappData['cert_pem']=0;//证书文件cert
            $wxappData['key_pem']=0;//证书文件key
            $wxappData['is_recycle']=0;//是否回收
            $wxappData['is_delete']=0;//是否删除
            $wxappData['create_time']=time();//创建时间
            $wxappData['update_time']=0;//更新时间
            $wxappData['active']=0;//账户激活（0，未激活，1.已激活）
            $wxappData['agent_id']=$loginInfo['loginUser']['agent_user_id'];//代理商id
            $wxappData['finish_time']=time()+8640000;//到期时间
            $wxappData['years']=1;//服务年限
            $wxappData['id_num']=input('post.id_num');//身份证号码
            $wxappData['wxapp_name']=input('post.shop_name');//商户名称

            $salt=Random::alnum();
            $wxappData['salt']=$salt;//密码盐
            $wxappData['password_confirm']=md5(md5(input('post.password').$salt.config('salt')));
            $wxappData['password']=md5(md5(input('post.password').$salt.config('salt')));//登录密码
            $wxappData['user_name']=input('post.user_name');//登录名称
            $wxappData['store_name']=input('post.shop_name');//商户wxapp名称
            $wxappData['realname']=input('post.realname');//法人姓名
            //$wxappData['category1']=input('post.industry1');//一级分类id
            //$wxappData['category2']=input('post.industry2');//二级分类id
            $wxappData['company_tel']=input('post.company_tel');//法人电话号码
            //$wxappData['data_type']=input('post.data_type');//1:小程序  2：公众号
            //$wxappData['service_type']=2;//1：龙达  2：公众号
            //if(input('post.merchant')){
               // $wxappData['merchant']=input('post.merchant');
           // }else{
              //  $wxappData['merchant']=1;
            //}
            $wxappData['realname']=input('post.realname');//法人姓名
            $wxappData['real_name']=input('post.realname');//store_user表姓名
            $wxappData['faren_num']=input('post.company_tel');//法人电话
            $wxappData['id_num']=input('post.id_num');//法人身份证号码
            $wxappData['id_img_face_id']=input('post.id_img_face_id');//法人身份证正面
            $wxappData['id_img_back_id']=input('post.id_img_back_id');//法人身份证背面
            $wxappModel=new WxappModel();
            $wxappId=$wxappModel->add($wxappData);
            //添加门店信息（store_shop表）
            $storeShop['shop_name']=input('post.shop_name');//门店名称
            $storeShop['logo_image_id']=input('post.image_id_mtz');//门店logo图片id
            $storeShop['linkman']=input('post.linkman');//联系人
            $storeShop['phone']=input('post.linkman');//联系电话
            $storeShop['shop_hours']=0;//营业时间
            $storeShop['province_id']='';//所在省份id
            $storeShop['city_id']='';//所在城市id
            $storeShop['region_id']='';//所在辖区id
            $storeShop['address']='';//详细地址
            $storeShop['longitude']=0;//门店坐标经度
            $storeShop['latitude']=0;//门店坐标纬度
            $storeShop['geohash']=0;//
            $storeShop['address']=input('post.address');//
            $storeShop['summary']='';//门店简介
            $storeShop['sort']=0;//门店排序(数字越小越靠前)
            $storeShop['is_check']=0;//是否支持自提核销(0否 1支持)
            $storeShop['status']=1;//门店状态(0禁用 1启用)
            $storeShop['is_delete']=0;//是否删除
            $storeShop['wxapp_id']=$wxappId;//小程序id
            $storeShop['create_time']=time();//创建时间
            $storeShop['update_time']=0;//更新时间
            $storeShop['image_id_gh']=input('post.image_id_gh');//公户照片
            $storeShop['image_id_mtz']=input('post.image_id_mtz');//门头照片
            $storeShop['image_id_yyzz']=input('post.image_id_yyzz');//营业执照
            $storeShop['image_id_dn']=input('post.image_id_dn');//店内照片
            $storeShop['logo_image_id']=input('post.head_img_id');//门店logo图片id
            Db::name('store_shop')->insertGetId($storeShop);
            Db::commit();
            return json(['msg'=>'进件成功','code'=>'success','data'=>[]]);
        } catch (\Exception $e) {
            Db::rollback();
            return json(['msg'=>'进件失败','code'=>'error','data'=>[]]);
        }
    }
    /*
     * 测试接口
     */
    public function test(){
        return json(['msg'=>'测试接口成功','status'=>'success','data'=>[]]);
    }
}
